#include "downloadbutton.h"

DownLoadButton::DownLoadButton(const QString& url,const QString& name,QPushButton *parent) : QPushButton(parent),filename(name)
{

    this->setText("下载");
    base_url=url+"download/";
    manager=new QNetworkAccessManager(this);
    connect(this,&QPushButton::clicked,this,&DownLoadButton::handerDownLoad);//连接下载处理函数
}

void DownLoadButton::handerDownLoad()
{

    // 构造请求对象
    QUrl url(base_url+filename);
    QNetworkRequest request(url); // 刷新页面请求
    // 发送请求
    response = manager->get(request);
    // 连接槽函数,处理响应
    connect(response, &QNetworkReply::finished, this,&DownLoadButton::downLoad);
}

void DownLoadButton::downLoad()
{
    if(response->error()!=QNetworkReply::NoError)
    {
        qDebug()<<"请求下载失败";
        return;
    }
    QString save_path=QFileDialog::getExistingDirectory(this);
    QFile file(save_path+"\\"+filename);//获取需要用QFileDialog指定文件保存路径
    if(!file.open(QIODevice::WriteOnly))qDebug()<<"打开失败";
    file.write(response->readAll());//将内容全部写入文件
    file.close();//写完关闭文件
}
